package com.tofine.smarthome.model;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import com.google.gson.annotations.SerializedName;

import org.parceler.Parcel;

import java.io.Serializable;
import java.util.List;

/**
 * @author ddMax
 * @since 2016/4/29 0:22.
 * 说明：设备实体类
 */
@Table(name = "Devices")
@Parcel
public class Device extends Model implements Serializable {

    @Column(name = "_id")
    public String _id;
    @Column(name = "image")
    @SerializedName("image_url")
    public String image;
    @Column(name = "name")
    public String name;
    @Column(name = "intro")
    public String intro;
    @Column(name = "status")
    public boolean status;
    @Column(name = "favorite")
    public boolean isFavorite;
    @Column(name = "category")
    public Category category;
    @Column(name = "room")
    public Room room;

    public List<Scene> scenes() {
        return getMany(Scene.class, "Device");
    }

    public Device() {}

    public Device(String _id, String image, String name, String intro, boolean status, boolean isFavorite) {
        this(_id, image, name, intro, status, isFavorite, null, null);
    }

    public Device(String _id, String image, String name, String intro, boolean status, boolean isFavorite, Category category, Room room) {
        this._id = _id;
        this.image = image;
        this.name = name;
        this.intro = intro;
        this.status = status;
        this.isFavorite = isFavorite;
        this.category = category;
        this.room = room;
    }

    public void setCategory(String categoryName) {
        if (categoryName == null)
            return;
        Category category = new Select().from(Category.class)
                .where("name = ?", categoryName)
                .executeSingle();
        this.category = category != null ? category : null;
    }

    public void setCategoryById(String id) {
        if (id == null)
            return;
        Category category = new Select().from(Category.class)
                .where("_id = ?", id)
                .executeSingle();
        this.category = category;
        this.category.save();
    }

    public void setRoomById(String id) {
        if (id == null)
            return;
        Room room = new Select().from(Room.class)
                .where("_id = ?", id)
                .executeSingle();
        this.room = room;
        this.room.save();
    }

    @Override
    public String toString() {
        return "Device{" +
                "_id='" + _id + '\'' +
                ", image='" + image + '\'' +
                ", name='" + name + '\'' +
                ", intro='" + intro + '\'' +
                ", status=" + status +
                ", isFavorite=" + isFavorite +
                ", category=" + category +
                ", room=" + room +
                '}';
    }
}
